//
//  SEGPGCDeteailManager.m
//  FrameworkTest
//
//  Created by 刘山 on 2018/4/24.
//  Copyright © 2018年 刘山. All rights reserved.
//

#import "SEGPGCDeteailManager.h"
#import "SEGChannelDetailModel.h"
#import "SEGPGCFixViewModel.h"
#import <SEGPlatform/SEGAdDisplayManager.h>

@interface SEGPGCDeteailManager ()
/**
 被举报的数据条数
 */
@property (nonatomic, assign) __block NSInteger reportedCount;
@property (nonatomic, assign) __block NSInteger adverIndx;

/// 主站列表总页数
@property (nonatomic, assign) __block NSInteger channelListTotalPage;

@end


@implementation SEGPGCDeteailManager

#pragma mark - PGC
/**
 * PGC喜欢头像的列表
 * @author Sam
 * @param objId  objId
 * @param objType  objType
 */
-(void)requestPGCLikeListWithObjId:(NSString*)objId objType:(NSString*)objType finished:(SEGNetworkReponse)finished{
    NSDictionary *params = @{@"objId":objId,@"objType":objType};
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/api/v2/likeIt",nil];

    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (!isSuccessed) {
            finished(NO,nil,codeType,errorMessage);
            return;
        }
        
        NSDictionary *data = [result valueForKey:@"data"];
        if (![data isKindOfClass:[NSDictionary class]]) {
            finished(NO,nil,codeType,errorMessage);
            return;
        }
        
        NSArray *likeIt = [data valueForKey:@"likeIt"];
        if (![likeIt isKindOfClass:[NSArray class]]) {
            finished(NO,nil,codeType,errorMessage);
            return;
        }
        NSMutableArray *arrM = [NSMutableArray array];
        [likeIt enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [arrM addObject:[obj valueForKey:@"icon"]];
        }];
        NSString *count = [data valueForKey:@"likeItCount"];
        
        SEGPGCFixViewModel *model = [SEGPGCFixViewModel new];
        model.likeCount = arrM;
        model.content = count;
        
        finished(YES,model,codeType,errorMessage);
    }];
}

/**
 * 请求广告
 * @author Sam
 */
-(void)requestADWithPositionType:(SEGAdvlistType)type finished:(SEGNetworkReponse)finished{
    [[SEGAdvlistManager sharedManager] segRequestAdvlistWithPositionType:type completed:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull codeType, NSString * _Nonnull errorMessage) {
        if (isSuccessed) {
            SEGAdvertisementViewModel *data = [[SEGAdvertisementViewModel alloc]init];
            data.adSource = result;
            data.communityName = kAccountCommunityName;
            if (type == SEGAdvlistType_SERVER){
                data.locationShowType = SEGEnumCommunityLocationViewType_Location;
            }
            finished(isSuccessed,data,codeType,errorMessage);
            return;
        }
        finished(NO,nil,codeType,errorMessage);
    }];
}

- (void)requestPgcDetailWithPictorialId:(NSString*)pictorialId finished:(SEGNetworkReponse)finished {
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/",kCMS_api,@"/pictorial/detail.json",nil];

    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:@{@"userId":kAccountUserID,@"pictorialId":pictorialId,@"code":@(SEGEnumAdvertismentIdType_PGC_LIST)} finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (!isSuccessed) {
            finished(NO,nil,codeType,errorMessage);
            return;
        }
        NSDictionary *data = [result valueForKey:@"data"];
        if (!data || ![data isKindOfClass:[NSDictionary class]] || data.count == 0) {
            finished(NO,nil,codeType,kMessageForArticleDeleted);
            return;
        }
        SEGPictorialDetailModel *pgcDetailModel = [SEGPictorialDetailModel yy_modelWithJSON:[data objectForKey:@"pictorial"]];
        self.pgcDetailModel = pgcDetailModel;
        finished(YES,nil,codeType,errorMessage);
    }];
}


/// 请求更多看点（该接口没有使用了）
/// @param objId objId
/// @param finished finished
- (void)requestMoreFocusWithObjId:(NSString *)objId finished:(SEGNetworkReponse)finished {
    
        NSDictionary *params = @{
                                 @"objId" : objId,
                                 @"channelId" : self.pgcDetailModel.channelId,
                                 };
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/api/v2/moreView",nil];

    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (!isSuccessed) {
            finished(NO,nil,codeType,errorMessage);
            return;
        }
        //接口未使用 暂不处理数据
//        NSDictionary *data = [result valueForKey:@"data"];
//        NSArray *moreViews = [data valueForKey:@"moreView"];
//        NSMutableArray *pgcLayouts = [NSMutableArray array];
//        for (NSDictionary *object in moreViews) {
//            SEGPgcRecommendModel *data = [SEGPgcRecommendModel yy_modelWithDictionary:object];
//            if([[object allKeys] containsObject:@"pic"]) data.pic = @[[object valueForKey:@"pic"]];
//            data.pictorialStyle = @"2";
//            SEGAutoTableViewCellLayout *layout = [[SEGAutoTableViewCellLayout alloc] initWithData:data type:SEGEnumAutoTableViewCellType_NO];
//            [pgcLayouts addObject:layout];
//        }
//
//        NSMutableArray *dataArrM = self.dataArrays.mutableCopy;
//        if(self.dataArrays.count > 1) {
//            [dataArrM replaceObjectAtIndex:1 withObject:pgcLayouts];
//        }
//        self.dataArrays = dataArrM;
        
        finished(YES,nil,codeType,errorMessage);
    }];
}

- (void)requestHotAndNormalCommentsWithObjId:(NSString *)objId objType:(NSString*)objType pageNo:(NSInteger)pageNo  finished:(SEGNetworkReponse)finished {
    [self requestHotCommentWithObjId:objId objType:objType finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (!finished) return;
        finished(YES,nil,codeType,errorMessage);
    }];
    [self requestCommentListWithObjId:objId objType:objType pageNo:pageNo finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (!finished) return;
        finished(YES,nil,codeType,errorMessage);
    }];
}

- (void)requestHotCommentWithObjId:(NSString*)objId objType:(NSString*)objType finished:(SEGNetworkReponse)finished {
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/api/v2/hotComment",nil];

    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:@{@"objId":objId,@"objType":objType} finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (!isSuccessed) {
            finished(NO,nil,codeType,errorMessage);
            return;
        }
        
        NSDictionary* dicData = [result valueForKey:@"data"];
        if ((!dicData) || (![dicData isKindOfClass:[NSDictionary class]])) {
            finished(NO,nil,codeType,errorMessage);
            return;
        }
        
        NSArray* list = [dicData valueForKey:@"comments"];
        
        if (!list || ![list isKindOfClass:[NSArray class]]) {
            finished(NO,nil,codeType,errorMessage);
            return;
        }
        
        NSMutableArray *comments = [NSMutableArray array];
        for (NSDictionary* dic in list) {
            SEGSharedCommentModel* _model = [SEGSharedCommentModel initWithDictionary:dic];
            [comments addObject:_model];
        }
        self.hotCommentArray = [comments copy];
        
        NSMutableArray *dataArrM = self.dataArrays.mutableCopy;
        if(self.dataArrays.count > 3) {
            [dataArrM replaceObjectAtIndex:3 withObject:comments];
        }
        self.dataArrays = dataArrM;
        
        finished(YES,comments,codeType,errorMessage);
    }];
}

- (void)requestCommentListWithObjId:(NSString*)objId objType:(NSString*)objType pageNo:(NSInteger)pageNo finished:(SEGNetworkReponse)finished {
    
    NSDictionary* params = @{
                             @"objId" : objId,
                             @"objType" : objType,
                             @"pageNo" : @(pageNo),
                             @"pageLimit" : @(10),
                             @"userId" : kAccountUserID
                             };
    
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/",kCMS_api,@"/bbs/queryComments",nil];

    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        if (!isSuccessed) {
            finished(NO,result,codeType,errorMessage);
            return;
        }
        
        NSDictionary* dicData = [result valueForKey:@"data"];
        if ((!dicData) || (![dicData isKindOfClass:[NSDictionary class]])) {
            finished(NO,nil,codeType,errorMessage);
            return;
        }
        
        NSArray* list = [dicData valueForKey:@"comments"];
        
        if (!list || ![list isKindOfClass:[NSArray class]]) {
            finished(NO,nil,codeType,errorMessage);
            return;
        }
        
//        if ([list isKindOfClass:[NSArray class]] && list.count == 0) {
//            finished(NO,nil,codeType,errorMessage);
//            return;
//        }
        if (pageNo == 1) { //顶部刷新
            self.commentsArray = [NSMutableArray array];
            self.reportedCount = 0;
        }
        
        for (NSDictionary* dic in list) {
            SEGSharedCommentModel* _model = [SEGSharedCommentModel initWithDictionary:dic];
            [self.commentsArray addObject:_model];
        }
        
        NSMutableArray *dataArrM = self.dataArrays.mutableCopy;
        if(self.dataArrays.count > 4) {
            [dataArrM replaceObjectAtIndex:4 withObject:self.commentsArray];
        }
        self.dataArrays = dataArrM;
        NSString *totalSize =  ValueToString([dicData objectForKey:@"totalSize"]);
        if(totalSize) {
            self.totalComment = [totalSize integerValue] - self.reportedCount;
        }else {
            self.totalComment = 0;
        }
        
        finished(YES,result,codeType,errorMessage);
    }];
}

/**
 * 删除评论
 * @author Wendy
 * @param commentId  评论id
 * @param objType  类型
 */
- (void)requestDeleteCommentWithCommentId:(NSString *)commentId objType:(NSString *)objType finished:(SEGRequestCallBack)finished
{
    NSDictionary *params = [[NSDictionary alloc] initWithObjectsAndKeys: commentId, @"objId", objType, @"objType", nil];
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/",kCMS_api,@"/bbs/deleteComment",nil];

    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if(isSuccessed) {
            //请求积分行为接口
            [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.replyIsDeleted finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            }];
        }
        finished(isSuccessed, codeType, errorMessage);
    }];
}

/**
 * 取消点赞
 * @author Wendy
 * @param objId 被取消对象ID
 * @param objType 被取消对象类型
 * @param finished 回调结果
 */
- (void)requestCancelPraiseByobjId:(NSString*)objId
                           objType:(NSString*)objType
                          Finished:(SEGRequestCallBack)finished
{
    //字典为空的闪退，数据校验
    NSDictionary* params = @{
                             @"userId" : kAccountUserID,
                             @"objId" : ValueToString(objId),
                             @"objType" : ValueToString(objType),
                             @"type" : @"3"
                             };
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/",kCMS_api,@"/praiseAttent/cancelPraiseOrCollect.json",nil];

    [SEGHTTPBusinessManager seg_requestWithMethod:POST URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        if (!isSuccessed) {
            finished(NO, codeType, errorMessage);
            return;
        }
        
        [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.cancelCollect finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        }];
        finished(YES, codeType, errorMessage);
    }];
}

/**
 * 对文章点赞
 * @author Wendy
 * @param objId    被点赞或浏览主题对象
 * @param objType  被点赞或浏览主题对象类型 1 画报2问题 3评论 4问题答案
 * @param finished 回调结果
 */
- (void)requestPraiseAttentByObjId:(NSString*)objId ObjType:(NSString*)objType Finished:(SEGRequestCallBack)finished
{
    //字典为空的闪退，数据校验
    NSDictionary* tempDict = @{
                               @"objId" : objId,
                               @"objType" : objType,
                               @"type" : @"3",
                               @"userId" : kAccountUserID,
                               //@"parentObjType" : parentObjType
                               };
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:tempDict];
    
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/",kCMS_api,@"/praiseAttent/save.json",nil];

    [SEGHTTPBusinessManager seg_requestWithMethod:POST URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (!isSuccessed) {
            finished(NO, codeType, errorMessage);
            return;
        }
        
        [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.addToFavorites module:SEGIntegralModule.articleDetail businessID:objId finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        }];
        finished(YES, codeType, errorMessage);
    }];
}

/**
 * 获取pgc单条评论的子评论
 * @author Wendy
 * @param objId objId
 * @param objType objType
 * @param sourceCommentId sourceCommentId
 */
- (void)requestChildCommentsWithObjId:(NSString*)objId objType:(NSString*)objType sourceCommentId:(NSString *)sourceCommentId finished:(SEGNetworkReponse)finished
{
    
    NSDictionary* params = @{
                             @"objId" : objId,
                             @"objType" : objType,
                             @"sourceCommentId" : sourceCommentId
                             };
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/api/v2/childComments",nil];

    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        if (!isSuccessed) {
            finished(NO,result,codeType,errorMessage);
            return;
        }
        
        NSDictionary* dicData = [result valueForKey:@"data"];
        if ((!dicData) || (![dicData isKindOfClass:[NSDictionary class]])) {
            finished(NO,nil,codeType,errorMessage);
            return;
        }
        
        NSArray* list = [dicData valueForKey:@"childComments"];
        
        if (!list || ![list isKindOfClass:[NSArray class]]) {
            finished(NO,nil,codeType,errorMessage);
            return;
        }

        finished(YES,result,codeType,errorMessage);
    }];
}

/**
 * 获取态度模式推荐PGC
 * @author Wendy
 * @param objId  objId
 */
- (void)requestRecommendPGCWithObjId:(NSString *)objId finished:(SEGNetworkReponse)finished {
    
    NSDictionary *params = @{
                             @"objId" : objId
                             };
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/api/v2/recommend",nil];

    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (!isSuccessed) {
            finished(NO,nil,codeType,errorMessage);
            return;
        }
        NSDictionary *data = [result valueForKey:@"data"];
        NSArray *moreViews = [data valueForKey:@"moreView"];
        
        self.recommendPGCArray = [NSMutableArray array];
        for (NSDictionary *object in moreViews) {
            SEGRecommendPGCModel *model = [SEGRecommendPGCModel yy_modelWithDictionary:object];
            [self.recommendPGCArray addObject:model];
        }
        
        finished(YES,nil,codeType,errorMessage);
    }];
}

/**
 * 对PGC评论进行 踩/顶 操作
 * @author Wendy
 * @param postId  帖子ID
 * @param post_type  帖子类型objType
 * @param commentId  评论ID
 * @param commentatorId  评论人ID
 * @param agreeOrDisagree  踩顶（1踩/2顶）
 */
- (void)requestStepOrTopPGCCommentWithPostId:(NSString *)postId
                                   post_type:(NSString *)post_type
                                   commentId:(NSString *)commentId
                               commentatorId:(NSString *)commentatorId
                             agreeOrDisagree:(NSString *)agreeOrDisagree
                                    finished:(SEGNetworkReponse)finished
{
    
    NSDictionary *params = @{
                             @"postId" : postId,
                             @"postType" : post_type,
                             @"commentId" : commentId,
                             @"commentatorId" : commentatorId,
                             @"agreeOrDisagree" : agreeOrDisagree
                             };
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/api/v3/commentAgreeOrDisagree",nil];

    [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        finished(isSuccessed, result, codeType, errorMessage);
        
    }];
}




//频道详情
-(void)requestChannelQuery:(NSString *)channelId PageNo:(NSInteger)pageNo PageLimit:(NSInteger)pageLimit Finished:(SEGNetworkReponse)finished{
    NSDictionary* params = @{
                             @"id" : channelId,
                             @"code": @(SEGEnumAdvertismentIdType_CHENNEL),
                             @"pageNo" : @(pageNo),
                             @"pageLimit" : @(10)
                             };
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/channel/channelQuery",nil];
    
    // 异常判断 请求的页面超过总页面则不再请求
    if (pageNo > 1) {
        if (pageNo > self.channelListTotalPage) {
            finished(NO,nil, 0, @"");
            return;
        }
    }

    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (!isSuccessed) {
            finished(isSuccessed,result, codeType, errorMessage);
            return ;
        }
         
        NSDictionary *data = [result valueForKey:@"data"];
        if (!data || ![data isKindOfClass:[NSDictionary class]]) {
            finished(NO,nil,codeType,errorMessage);
            return;
        }
        
        // 记录主站列表page总数
        self.channelListTotalPage = [result[@"data"][@"totalPage"] integerValue];
        
        NSDictionary *channelDict = [data valueForKey:@"channelDetail"];
        if (!channelDict || ![channelDict isKindOfClass:[NSDictionary class]]) {
            finished(NO,nil,codeType,errorMessage);
            return;
        }
        
        self.channelmodel = [SEGChannelDetailModel yy_modelWithJSON:channelDict];
        NSMutableArray<SEGPgcRecommendModel *> *pgcListArr = [[NSArray yy_modelArrayWithClass:[SEGPgcRecommendModel class] json:[data valueForKey:@"pgcList"]] mutableCopy];
        [pgcListArr enumerateObjectsUsingBlock:^(SEGPgcRecommendModel *pgcmodel, NSUInteger idx, BOOL * _Nonnull stop) {
            pgcmodel.channelName = @"";//频道主站不显示主站名称
            pgcmodel.pgcWidgetType = @(SEGEnumPgcWidgetType_PGC).stringValue;
        }];
        
        if (pageNo == 1) {
            self.adverIndx = 0;
        }
        
        // 读取配置 插入广告
        if ([[SEGAdDisplayManager shared] getAdWhetherShow:SEGAD_ChannelListType]) {
            SEGPgcRecommendModel *adData = [SEGPgcRecommendModel new];
            adData.adverIndex = self.adverIndx;
            adData.pgcWidgetType = @(SEGEnumPgcWidgetType_AD).stringValue;
            self.adverIndx ++;
            // [5.0.0需求]广告固定第四位展示，一组数据不足3条，则广告不展示
            if (pgcListArr.count > 3) {
                [pgcListArr insertObject:adData atIndex:3];
            }
        }
        
        //判断是否只有单页数据
        if(pageNo == 1){
            self.channelDataArrays = [pgcListArr copy];;
        }else {
            self.channelDataArrays = [self.channelDataArrays arrayByAddingObjectsFromArray:pgcListArr];
        }
        
        finished(isSuccessed,result, codeType, errorMessage);
    }];
}

#pragma mark - getter
- (NSArray<NSArray *> *)dataArrays {
    if (!_dataArrays) {
        _dataArrays = @[@[],@[],@[],@[],@[]];//0.喜欢列表及广告 1.更多看点 2.腾讯广告 3.热门评论 4.评论
    }
    return _dataArrays;
}

- (NSMutableArray<SEGSharedCommentModel *> *)commentsArray {
    if (!_commentsArray) {
        _commentsArray = [NSMutableArray array];
    }
    return _commentsArray;
}

- (NSMutableArray<SEGRecommendPGCModel *> *)recommendPGCArray {
    if (!_recommendPGCArray) {
        _recommendPGCArray = [NSMutableArray array];
    }
    return _recommendPGCArray;
}

@end

